package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.li.work.domain.vo.WorkDeptUserVO;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.PlatformFFeedback;
import com.ruoyi.teaching.domain.PlatformFFeedbackLike;
import com.ruoyi.teaching.domain.PlatformFForum;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.domain.dto.feedbackFrontDownSortDTO;
import com.ruoyi.teaching.domain.vo.*;
import com.ruoyi.teaching.mapper.PlatformFFeedbackLikeMapper;
import com.ruoyi.teaching.mapper.PlatformFFeedbackMapper;
import com.ruoyi.teaching.service.PlatformFFeedbackService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2025-02-12
 */
@Service
public class PlatformFFeedbackServiceImpl extends ServiceImpl<PlatformFFeedbackMapper, PlatformFFeedback> implements PlatformFFeedbackService {
    @Autowired
    private PlatformFFeedbackMapper platformFFeedbackMapper;
    @Autowired
    private PlatformFFeedbackLikeMapper platformFFeedbackLikeMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public AjaxResult frontUp(Integer pageNum, Integer pageSize, Integer feedbackStatus) {
        Page<PlatformFFeedback> platformFFeedbackPage = new Page<>(pageNum, pageSize);
        Page<PlatformFFeedback> feedbackAllPage = platformFFeedbackMapper.selectPageFrontUp(platformFFeedbackPage, feedbackStatus);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", feedbackAllPage);
    }

    // /**
    //  * @param pageNum
    //  * @param pageSize
    //  * @param sorts    和前端约定好fieldName字段time是时间look是浏览量reply是回复
    //  * @return
    //  */
    @Override
    public AjaxResult frontDown(Integer pageSize, Integer pageNum, Integer replySort, Integer lookSort, Integer timeSort, String title, Integer feedbackStatus) {
        Page<FeedbackFrontDownSortVO> page = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFFeedback> queryWrapper = new QueryWrapper<>();

        // // 处理排序逻辑
        // if (CollectionUtils.isNotEmpty(sorts)) {
        //     sorts.sort(Comparator.comparing(feedbackFrontDownSortDTO::getPriority).reversed());
        //     for (feedbackFrontDownSortDTO sortDTO : sorts) {
        //         String field = sortDTO.getFieldName();
        //         boolean isAsc = sortDTO.getSort() == 1;
        //
        //         // 处理排序字段
        //         switch (field) {
        //             case "replyNum":
        //                 queryWrapper.orderBy(true, isAsc, "reply_count");
        //                 break;
        //             case "likeNum":
        //                 queryWrapper.orderBy(true, isAsc, "like_num");
        //                 break;
        //             case "lookNum":
        //                 queryWrapper.orderBy(true, isAsc, "look_num");
        //                 break;
        //             case "createTime":
        //                 queryWrapper.orderBy(true, isAsc, "create_time");
        //                 break;
        //         }
        //     }
        // } else {
        //     // 默认按 点亮数量 排序
        //     queryWrapper.orderByDesc("like_num").orderByDesc("look_num").orderByDesc("replyNum").orderByDesc("create_time");
        // }
        //
        // // 执行查询
        // Page<FeedbackFrontDownSortVO> feedbackList = platformFFeedbackMapper.selectFeedbackWithReplyCount(page, queryWrapper);
        // 处理排序逻辑
        if (replySort != null) {
            if (replySort == 0) {
                queryWrapper.orderByDesc("replyNum");
            } else if (replySort == 1) {
                queryWrapper.orderByAsc("replyNum");
            }
        } else if (lookSort != null) {
            if (lookSort == 0) {
                queryWrapper.orderByDesc("look_num");
            } else if (lookSort == 1) {
                queryWrapper.orderByAsc("look_num");
            }
        } else if (timeSort != null) {
            if (timeSort == 0) {
                queryWrapper.orderByDesc("create_time");
            } else if (timeSort == 1) {
                queryWrapper.orderByAsc("create_time");
            }
        } else {
            // 默认排序规则
            queryWrapper.orderByDesc("like_num")
                    .orderByDesc("look_num")
                    .orderByDesc("replyNum")
                    .orderByDesc("create_time");
        }

        Page<FeedbackFrontDownSortVO> feedbackList = platformFFeedbackMapper.selectFeedbackWithReplyCount(page, queryWrapper, title, feedbackStatus);

        // 添加点亮用户信息
        List<FeedbackFrontDownSortVO> records = feedbackList.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            for (FeedbackFrontDownSortVO record : records) {
                Long projectId = record.getId();
                List<WorkDeptUserVO> uersInfoList = platformFFeedbackLikeMapper.selectFeedbcakLikeUserInfos(projectId);
                record.setUersInfoList(uersInfoList);
            }
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", feedbackList);
    }

    /**
     * @param objectId 查询的对象id
     * @param type     从哪里看详情（0帖子1点赞2评论）
     * @return
     */
    @Override
    public AjaxResult detail(Long objectId, Integer type) {
        if (null == type) {
            return new AjaxResult(HttpStatus.ERROR, "非法获取");
        }
        if (type == 1) {
            PlatformFFeedbackLike platformFFeedbackLike = platformFFeedbackLikeMapper.selectById(objectId);
            if (platformFFeedbackLike == null) {
                return new AjaxResult(HttpStatus.ERROR, "该点赞已被删除");
            }
            Long objectId1 = platformFFeedbackLike.getObjectId();
            FeedbackDetailVO feedbackDetailVO = platformFFeedbackMapper.selectDetailById(objectId1);
            if (null == feedbackDetailVO) {
                return new AjaxResult(HttpStatus.ERROR, "该反馈已被删除");
            }
            // 将图片改为数组
            String[] img = feedbackDetailVO.getImageUrl().split(",");
            feedbackDetailVO.setImageUrlList(Arrays.asList(img));

            // 添加本人是否点赞信息
            insertOwnLikeInfo(feedbackDetailVO);

            // 添加用户信息
            Long createId = feedbackDetailVO.getCreateId();
            SysUser user = userMapper.selectUserById(createId);
            if (null != user) {
                if (null != user.getAvatar()) {
                    feedbackDetailVO.setAvatar(user.getAvatar());
                }
                if (null != user.getNickName()) {
                    feedbackDetailVO.setNickName(user.getNickName());
                }
            }
            feedbackDetailVO.setLookNum(feedbackDetailVO.getLookNum() + 1);
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", feedbackDetailVO);
        }
        if (type == 0 || type == 2) {
            PlatformFFeedback platformFFeedback = platformFFeedbackMapper.selectById(objectId);
            if (platformFFeedback == null) {
                return new AjaxResult(HttpStatus.ERROR, "该反馈已被删除");
            }
            if (null != platformFFeedback.getTopId()) {
                objectId = platformFFeedback.getTopId();
            }
            FeedbackDetailVO feedbackDetailVO = platformFFeedbackMapper.selectDetailById(objectId);
            if (feedbackDetailVO == null) {
                return new AjaxResult(HttpStatus.ERROR, "该反馈已被删除");
            }
            // 添加本人是否点赞信息
            insertOwnLikeInfo(feedbackDetailVO);
            // 将图片改为数组
            String[] img = feedbackDetailVO.getImageUrl().split(",");
            feedbackDetailVO.setImageUrlList(Arrays.asList(img));
            // 添加用户信息
            Long createId = feedbackDetailVO.getCreateId();
            SysUser user = userMapper.selectUserById(createId);
            if (null != user) {
                if (null != user.getAvatar()) {
                    feedbackDetailVO.setAvatar(user.getAvatar());
                }
                if (null != user.getNickName()) {
                    feedbackDetailVO.setNickName(user.getNickName());
                }
            }
            feedbackDetailVO.setLookNum(feedbackDetailVO.getLookNum() + 1);
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", feedbackDetailVO);
        }
        return new AjaxResult(HttpStatus.ERROR, "非法获取");
    }

    private void updateLookNum(Long objectId, Integer lookNum) {
        PlatformFFeedback platformFFeedback = new PlatformFFeedback();
        platformFFeedback.setId(objectId);
        platformFFeedback.setLookNum(lookNum + 1);
        platformFFeedbackMapper.updateById(platformFFeedback);
    }

    @Override
    public AjaxResult commentList(Long feedbackId, Integer pageNum, Integer pageSize) {
        QueryWrapper<PlatformFFeedback> platformFFeedbackQueryWrapper = new QueryWrapper<>();
        platformFFeedbackQueryWrapper.eq("top_id", feedbackId);
        List<PlatformFFeedback> platformFFeedbacks = platformFFeedbackMapper.selectList(platformFFeedbackQueryWrapper);
        ArrayList<CommentVO> commentVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(platformFFeedbacks)) {
            for (PlatformFFeedback platformFFeedback : platformFFeedbacks) {
                CommentVO commentVO = new CommentVO();
                BeanUtils.copyProperties(platformFFeedback, commentVO);
                // 添加用户信息
                Integer createId = commentVO.getCreateId();
                SysUser user = userMapper.selectUserById(Long.valueOf(createId));
                if (null != user) {
                    if (null != user.getAvatar()) {
                        commentVO.setAvatar(user.getAvatar());
                    }
                    if (null != user.getNickName()) {
                        commentVO.setNickName(user.getNickName());
                    }
                }
                commentVOS.add(commentVO);
            }
            // 过滤出顶级评论（即没有 topCommentId 的评论）
            List<CommentVO> topLevelComments = commentVOS.stream()
                    .filter(forumVO -> forumVO.getTopCommentId() == null)
                    .collect(Collectors.toList());

            // 为每个顶级评论找到其子评论，并设置到 VO 的 children 属性中
            for (CommentVO topComment : topLevelComments) {
                List<CommentVO> childComments = commentVOS.stream()
                        .filter(forumVO -> forumVO.getTopCommentId() != null && forumVO.getTopCommentId().equals(topComment.getId()))
                        .collect(Collectors.toList());
                topComment.setChildren(childComments);
                topComment.setReplyCount(childComments.size());
            }
            // 确定分页参数
            int total = topLevelComments.size();
            if (pageNum == null || pageNum < 1) {
                pageNum = 1;
            }
            if (pageSize == null || pageSize < 1) {
                pageSize = 10;
            }
            int start = Math.min((pageNum - 1) * pageSize, total);
            int end = Math.min(start + pageSize, total);

            // 获取当前页的数据
            List<CommentVO> paginatedList = topLevelComments.subList(start, end);

            // 设置分页信息
            Page<CommentVO> page = new Page<>(pageNum, pageSize);
            page.setRecords(paginatedList);
            page.setTotal(total);
            return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
        }
        return new AjaxResult(HttpStatus.SUCCESS, "暂无评论");
    }

    @Override
    public AjaxResult addFeedbackOrComment(PlatformFFeedback platformFFeedback) {
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(userMapper);
        platformFFeedback.setCreateBy(update.getName());
        platformFFeedback.setCreateTime(DateUtils.getNowDate());
        platformFFeedback.setCreateId(update.getId());
        int insert = platformFFeedbackMapper.insert(platformFFeedback);
        if (insert > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "发布成功");
        }
        return new AjaxResult(HttpStatus.ERROR, "发布失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteFeedbackOrComment(Long[] ids) {
        Long userId = SecurityUtils.getUserId();
        int roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6); // 超级管理员

        if (roleSystemAdmin) {
            int deletedCount = 0;
            for (Long id : ids) {
                PlatformFFeedback platformFFeedback = platformFFeedbackMapper.selectById(id);
                int rowsDeleted = platformFFeedbackMapper.deleteById(id);
                if (rowsDeleted > 0) {
                    deletedCount++;
                    if(platformFFeedback.getTopCommentId() == null && platformFFeedback.getTopId() != null){
                        platformFFeedbackMapper.delete(new QueryWrapper<PlatformFFeedback>().eq("top_comment_id", id));
                    }
                }
            }
            if (deletedCount == ids.length) {
                return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "删除失败");
            }
        } else {
            int successfulDeletions = 0;
            for (Long id : ids) {
                PlatformFFeedback platformFFeedback = platformFFeedbackMapper.selectById(id);
                if (platformFFeedback != null) {
                    if (platformFFeedback.getTopId() != null) {
                        PlatformFFeedback platformFFeedbackTop = platformFFeedbackMapper.selectById(platformFFeedback.getTopId());
                        if (platformFFeedbackTop != null && platformFFeedbackTop.getCreateId() != null) {
                            if (platformFFeedbackTop.getCreateId().equals(userId.intValue())) {
                                int rowsDeleted = platformFFeedbackMapper.deleteById(id);
                                if (rowsDeleted > 0) {
                                    successfulDeletions++;
                                    if(platformFFeedback.getTopCommentId() == null && platformFFeedback.getTopId() != null){
                                        platformFFeedbackMapper.delete(new QueryWrapper<PlatformFFeedback>().eq("top_comment_id", id));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (successfulDeletions == ids.length) {
                return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
            } else {
                throw new RuntimeException("无法删除他人数据");
            }
        }
    }

    @Override
    public AjaxResult myFeedback(Integer pageNum, Integer pageSize, String title, Integer feedbackStatus, Long feedbackType, Integer time) {
        Page<FeedbackDetailVO> feedbackDetailVOPage = new Page<>(pageNum, pageSize);
        LocalDateTime startDate = UniversalUtil.getStartDate(time);
        Long userId = SecurityUtils.getUserId();
        Page<FeedbackDetailVO> myFeedbackVOs = platformFFeedbackMapper.selectMyFeedback(feedbackDetailVOPage, title, feedbackStatus, feedbackType, startDate, userId);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", myFeedbackVOs);
    }

    /**
     * 该接口仿照PlatformFForumServiceImpl.ownCommentList
     */
    @Override
    public AjaxResult myCommentList(Integer pageNum, Integer pageSize, Integer type) {
        // 分页参数构造，设置分页查询的页码和每页大小
        Page<PlatformFFeedback> feedbackPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFFeedback> queryWrapper = new QueryWrapper<>();

        // 获取当前登录用户的 ID
        Long userId = SecurityUtils.getUserId();

        // 查询所有非帖子，type 为0看我的评论，1为我收到的评论（此处代码为非0都是我收到的评论，默认是我的评论）
        if (null == type) {
            type = 0;
        } else if (type > 1) {
            type = 0;
        }
        queryWrapper.eq(type == 0 ? "create_id" : "reply_user_id", userId).isNotNull("top_id").orderByDesc("create_time");

        // 分页查询评论
        Page<PlatformFFeedback> resultPage = platformFFeedbackMapper.selectPage(feedbackPage, queryWrapper);

        Page<FeedBackOwnCommentVO> feedBackOwnCommentVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(resultPage, feedBackOwnCommentVOPage);

        List<FeedBackOwnCommentVO> feedBackOwnCommentVOList = new ArrayList<>();

        for (PlatformFFeedback record : resultPage.getRecords()) {
            FeedBackOwnCommentVO feedBackOwnCommentVO = new FeedBackOwnCommentVO();
            BeanUtils.copyProperties(record, feedBackOwnCommentVO);

            // 获取回复用户的昵称并设置到 VO 中
            Long replyUserId = type == 0 ? feedBackOwnCommentVO.getReplyUserId() : Long.valueOf(feedBackOwnCommentVO.getCreateId());
            String replyUserName = "";
            if (userId == replyUserId) {
                replyUserName = "我";
            } else {
                SysUser user = userMapper.selectUserById(replyUserId);
                replyUserName = user != null ? user.getNickName() : "用户不存在";
                feedBackOwnCommentVO.setReplyUserName(replyUserName);
            }

            // 根据评论是否为顶级评论设置标题或评论内容
            if (feedBackOwnCommentVO.getTopCommentId() == null) {
                // 如果没有顶级评论 ID，说明该评论是针对帖子，获取帖子标题
                PlatformFFeedback feedback = platformFFeedbackMapper.selectById(feedBackOwnCommentVO.getTopId());
                String parentMessage = feedback != null ? feedback.getTitle() : "帖子已被删除";
                feedBackOwnCommentVO.setCommentTitle(type == 0 ? replyUserName + "：" + parentMessage : "我：" + parentMessage);
            } else {
                // 否则获取该评论的父评论内容
                PlatformFFeedback forum = platformFFeedbackMapper.selectById(feedBackOwnCommentVO.getCommentId());
                String parentMessage = forum != null ? forum.getMessage() : "评论已被删除";
                feedBackOwnCommentVO.setCommentTitle(type == 0 ? replyUserName + "：" + parentMessage : "我：" + parentMessage);
            }
            if (type != 0) {
                feedBackOwnCommentVO.setMessage(replyUserName + "：" + feedBackOwnCommentVO.getMessage());
            }

            SysUser user = userMapper.selectUserById(Long.valueOf(feedBackOwnCommentVO.getCreateId()));
            if (null != user) {
                if (null != user.getAvatar()) {
                    feedBackOwnCommentVO.setCreateUrl(user.getAvatar());
                }
            }
            feedBackOwnCommentVOList.add(feedBackOwnCommentVO);

            feedBackOwnCommentVOPage.setRecords(feedBackOwnCommentVOList);
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", feedBackOwnCommentVOPage);
    }

    @Override
    public AjaxResult backAllFeedback(Integer pageNum, Integer pageSize, String title, Integer feedbackStatus, Long feedbackType, Integer time) {
        Page<FeedbackDetailVO> feedbackDetailVOPage = new Page<>(pageNum, pageSize);
        LocalDateTime startDate = UniversalUtil.getStartDate(time);
        Page<FeedbackDetailVO> myFeedbackVOs = platformFFeedbackMapper.selectMyFeedback(feedbackDetailVOPage, title, feedbackStatus, feedbackType, startDate, null);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", myFeedbackVOs);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult updateFeedback(List<PlatformFFeedback> platformFFeedbackList) {
        int i = 0;
        for (PlatformFFeedback platformFFeedback : platformFFeedbackList) {
            int i1 = platformFFeedbackMapper.updateById(platformFFeedback);
            if (i1 > 0) {
                i++;
            }
        }
        if (i == platformFFeedbackList.size()) {
            return new AjaxResult(HttpStatus.SUCCESS, "操作成功");
        }
        throw new RuntimeException("操作失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteFeedback(Long[] ids) {
        int i1 = 0;
        for (Long id : ids) {
            PlatformFFeedback platformFFeedback = platformFFeedbackMapper.selectById(id);
            int i = platformFFeedbackMapper.deleteById(id);
            if (i > 0) {
                i1++;
                if(platformFFeedback.getTopCommentId() == null && platformFFeedback.getTopId() != null){
                    platformFFeedbackMapper.delete(new QueryWrapper<PlatformFFeedback>().eq("top_comment_id", id));
                }
            }
        }
        if (i1 == ids.length) {
            return new AjaxResult(HttpStatus.SUCCESS, "操作成功");
        }
        throw new RuntimeException("操作失败");
    }

    @Override
    public AjaxResult addLookCount(Long feedbackId) {
        FeedbackDetailVO feedbackDetailVO = platformFFeedbackMapper.selectDetailById(feedbackId);
        // 增加帖子浏览量
        updateLookNum(feedbackId, feedbackDetailVO.getLookNum());
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功");
    }


    private void insertOwnLikeInfo(FeedbackDetailVO feedbackDetailVO) {
        Long feedbackId = feedbackDetailVO.getId();
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<PlatformFFeedbackLike> platformFFeedbackLikeQueryWrapper = new QueryWrapper<>();
        platformFFeedbackLikeQueryWrapper.eq("object_id", feedbackId).eq("create_id", userId);
        List<PlatformFFeedbackLike> platformFFeedbackLikes = platformFFeedbackLikeMapper.selectList(platformFFeedbackLikeQueryWrapper);
        if (CollectionUtils.isNotEmpty(platformFFeedbackLikes)) {
            feedbackDetailVO.setIsLike(1);
        } else {
            feedbackDetailVO.setIsLike(0);
        }
    }

}
